package com.example.tt_bells_v02;

import java.util.List;

import net.simonvt.widget.CalendarView;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.text.format.Time;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class ActivityMain extends Activity implements OnClickListener {

	CalendarView cv;
	Button sbut;
	Button abut;
	ServiceConnection sconn;
	BellManager bm;
	boolean bound = false;
	//Intent srv_intent;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		cv = (CalendarView)findViewById(R.id.cv_main);
	
		this.setTitle("Bells manager");
	
		sbut = (Button)findViewById(R.id.service_runstop);
		sbut.setOnClickListener(this);
		abut = (Button)findViewById(R.id.service_activate);
		abut.setOnClickListener(this);	
		
		//cv.setOnDateChangeListener(this);
/*
        if(tStartService) {
                startService(new Intent(ctx, BellManager.class));
        }
        */
		//srv_intent = new Intent("CARAMBA");
		sconn = new ServiceConnection() {
		      public void onServiceConnected(ComponentName name, IBinder binder) {
		        Log.d("BELL: ", "MainActivity onServiceConnected");
		        bm = ((BellManager.MyBinder)binder).getService();
		        bound = true;
		      }

		      public void onServiceDisconnected(ComponentName name) {
		        Log.d("BELL: ", "MainActivity onServiceDisconnected");
		        bound = false;
		      }
		};
		
		if (checkServiceStarted()) {
			bindService(new Intent(this, BellManager.class), sconn, BIND_AUTO_CREATE);
		}
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		
		if (bound) unbindService(sconn);
	};
	
	@Override
	protected void onResume() {
		super.onResume();
		
		updateServiceView(checkServiceStarted());
	}
	
	public void updateServiceView(boolean active) {
		TextView stv = (TextView)findViewById(R.id.service_state);
		
		if (active) {
			stv.setText("Service is running");
			sbut.setText("Stop");
		} else {
			stv.setText("Service is stopped");
			sbut.setText("Run");
		}
	}
	
	public boolean checkServiceStarted() {
		String serviceName = BellManager.class.getName();		
        ActivityManager am = (ActivityManager)this.getSystemService(ACTIVITY_SERVICE);
        Log.d(Tag.TAG, "checkServiceStarted for "+ serviceName);
        
        //TODO: get the real number of running services or make a cycle (if possible)
        List<ActivityManager.RunningServiceInfo> rs = am.getRunningServices(50);
        for (int i=0; i<rs.size(); i++) {
              	ActivityManager.RunningServiceInfo rsi = rs.get(i);
                if(serviceName.equalsIgnoreCase(rsi.service.getClassName())){
                	Log.d(Tag.TAG,"Service is already started: "+rsi.service.getClassName());
                	return true;
                }              
        }
        return false;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menu_edit_month, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.mim_clear) {
			Intent aaa = new Intent(cv.getContext(),ActivityDeleteBell.class);
			aaa.putExtra("edit_type", BellInfo.EDIT_MONTH);
			startActivityForResult(aaa, 0);
		}
		return true;
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			boolean do_delete = data.getBooleanExtra("delete", false);
			if (do_delete) {
				int edit_type = data.getIntExtra("edit_type", BellInfo.EDIT_MONTH);
				Time selected_time = new Time(Time.getCurrentTimezone());
				selected_time.set(cv.getDate());
				Log.d(Tag.TAG,"selected month "+selected_time.month+" and year "+selected_time.year);
				if (edit_type == BellInfo.EDIT_MONTH) {
					for (Bell element : bm.bellHolder) {
						if ((element.alarm_time.month == selected_time.month) &&
							(element.alarm_time.year == selected_time.year)) { //delete
							bm.bellHolder.remove(element);
						}
					}
				}
			}
		}	
	}
	
	
	@Override
	public void onClick(View v) {
		//Log.d(Tag.TAG, " date "+cv.getDate());
		switch (v.getId()) {
			case R.id.service_runstop: {
				if (checkServiceStarted()) {
					if (bound) unbindService(sconn);
					stopService(new Intent(this, BellManager.class));
					bound = false;
				} else {
					startService(new Intent(this, BellManager.class));
					bindService(new Intent(this, BellManager.class), sconn, BIND_AUTO_CREATE);
				}
				updateServiceView(checkServiceStarted());
			break; }
			case R.id.service_activate: {
				if (checkServiceStarted()) {
					bm.syncUpdate();					
				}
			break; }
		}
	}

}
